import IpGetter
import platform
import  subprocess
import json
from AcsClientSingleton import AcsClientSing
from CommonRequestSingleton import CommonRequestSing
import os

class Utils:
    #获取真实公网IP
    def getRealIP(self):
        # print("-----------------------")
        url = IpGetter.getIpPage()
        print(url)
        ip = IpGetter.getRealIp(url)
        # ip = "116.235.54.109"
        return ip

    #获取真实公网IPv6
    def getRealIPv6(self):
        url = IpGetter.getIpPageV6()
        ip = IpGetter.getRealIpV6(url)
        # print(ip)
        return ip

    #获取二级域名的RecordId
    def getRecordId(self,domain):
        client = Utils().getAcsClient()
        request = Utils().getCommonRequest()
        request.set_domain('alidns.aliyuncs.com')
        request.set_version('2015-01-09')
        request.set_action_name('DescribeDomainRecords')
        request.add_query_param('DomainName', Utils().getConfigJson().get('First-level-domain'))
        response = client.do_action_with_exception(request)
        jsonObj = json.loads(response.decode("UTF-8"))
        records = jsonObj["DomainRecords"]["Record"]
        for each in records:
            if each["RR"] == domain:
                return each["RecordId"]

    #获取CommonRequest
    def getCommonRequest(self):
        return CommonRequestSing.getInstance()

    #获取AcsClient
    def getAcsClient(self):
        return AcsClientSing.getInstance()

    #获取操作系统平台
    def getOpeningSystem(self):
        return platform.system()

    #判断是否联网
    def isOnline(self):
        userOs = Utils.getOpeningSystem(self)
        try:
            if userOs == "Windows":
                subprocess.check_call(["ping", "-n", "2", "www.baidu.com"], stdout=subprocess.PIPE)
            else:
                subprocess.check_call(["ping", "-c", "2", "www.baidu.com"], stdout=subprocess.PIPE)
            return True
        except subprocess.CalledProcessError:
            print("网络未连通！请检查网络")
            return False

    #从config.json中获取配置信息JSON串
    def getConfigJson(self):
        path = os.path.dirname(__file__)
        # print(1111111,path)
        with open(path+'\\config.json') as file:
            jsonStr = json.loads(file.read())
            # print(jsonStr)
        return jsonStr
